#include <QtGui>
#include <QtNetwork>
#include <iostream>

#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "tdownlad.h"

MainWindow::MainWindow(QWidget *parent) :
    QWidget(parent), ui(new Ui::MainWindow), isFullCheck(false)
{
    ui->setupUi(this);
    ui->webView->load(QUrl("http://l2nemerian.seobrya.com/updater/"));
    connect(ui->quit_boutton, SIGNAL(clicked()), this, SLOT(my_quit()));
    connect(ui->start_boutton, SIGNAL(clicked()), this, SLOT(execute()));
    connect(ui->FC_boutton, SIGNAL(clicked()), this, SLOT(fullCheck()));
    connect(this, SIGNAL(startNextDl()), this, SLOT(nextDl()));
    ui->FC_boutton->setEnabled(false);
    ui->start_boutton->setEnabled(false);
    ui->total_pbar->setMaximum(1);
    file_dl = 0;

    MainWindow::setWindowIcon(QIcon(":ressources/Logo.jpg"));
    QSystemTrayIcon *trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon(QIcon(":ressources/Logo.jpg"));
    trayIcon->show();

}

MainWindow::~MainWindow()
{
    delete ui;
}

QString MainWindow::CalcSha1(QString Path)
{
        QFile FileToHash(Path);
        QByteArray ba;
        QString HashOutput;
        QCryptographicHash CPU(QCryptographicHash::Sha1);
        if (FileToHash.open(QIODevice::ReadOnly))
        {
                while (!FileToHash.atEnd())
                {
                        ba = FileToHash.read(1024);
                        CPU.addData(ba);
                }
                FileToHash.close();
                ba = CPU.result();
                HashOutput = ba.toHex();
                return HashOutput;
        }
        else
        {
                HashOutput = "ERR";
                return HashOutput;
        }
}
void MainWindow::downloadlst()
{
    TDownlad *dlst = new TDownlad(0, QString("update.lst"));
    connect(dlst, SIGNAL(updateProgress(int, int)), this, SLOT(updateDataReadProgress(int,int)));
    connect(dlst, SIGNAL(updateSl(QString)), this, SLOT(updateStatus(QString)));
    ui->statusLabel->setText(tr("Downloading."));
    dlst->start();
    dlst->wait();
    QEventLoop loop;
    connect(dlst, SIGNAL(done()), &loop, SLOT(quit()));
    loop.exec();
    delete dlst;
    this->get_CUpdate();
}

void MainWindow::updateStatus(QString text)
{
    ui->statusLabel->setText(text);
}

void MainWindow::get_CUpdate()
{
    ui->statusLabel->setText(tr("Downloading Critical update."));
    QString fileName("update.lst");
    QFile fichier(fileName);
    fichier.open(QIODevice::ReadOnly);
    QTextStream flux(&fichier);
    QString ligne;
    while(!flux.atEnd())
    {
        ligne = flux.readLine();
        if (ligne == "[misc]")
        {
            ligne = flux.readLine();
            addr_server = ligne.section('=', 1, 1);
        }
        else if (ligne == "[files]")
        {
            ligne = flux.readLine();
            file_count = ligne.section('=', 1, 1).toInt();
            int i = 0;
            while (i < file_count)
            {
                ligne = flux.readLine();
                if (ligne.section('|', 2, 2) == "c")
                {
                    if (CalcSha1(ligne.section('|', 0, 0).section('=', 1, 1)) != ligne.section('|', 1, 1)){
                        file_list.append(ligne.section('=', 1, 1).section('|', 0, 0));
                    }
                }
                i++;
            }
        }
    }
    QStringListModel *modele = new QStringListModel(file_list);
    ui->lv->setModel(modele);
    ui->total_pbar->setMaximum(file_list.size());
    ui->total_pbar->setValue(0);
    if (file_list.size() == 0){
        ui->total_pbar->setMaximum(1);
        ui->total_pbar->setValue(ui->total_pbar->maximum());
    }
    else
    {
        iterator = 0;
        this->nextDl();
    }
    ui->statusLabel->setText(tr("your application is up to date click on sart for launch"));
    ui->FC_boutton->setEnabled(true);
    ui->start_boutton->setEnabled(true);
}

#include <QTimer>

void MainWindow::nextDl()
{
    if(isFullCheck)
    {
        ui->statusLabel->setText(file_list.at(iterator));
        qDebug()<< "entry iterator: " << iterator;
        TDownlad *dlst = new TDownlad(0, file_list.at(iterator),hash_list.at(iterator));
            connect(dlst, SIGNAL(updateProgress(int, int)), this, SLOT(updateDataReadProgress(int,int)));
            dlst->start();
            iterator++;
            QEventLoop loop;
            qDebug("in wait done loop");
            connect(dlst, SIGNAL(done()), &loop, SLOT(quit()));
            connect(dlst, SIGNAL(sdlerror()), this, SLOT(dlError()));
            loop.exec();
            qDebug("end wait done loop");
            dlst->wait();
            delete(dlst);
            if (iterator != file_list.size())
                emit startNextDl();
            ui->total_pbar->setValue(ui->total_pbar->value()+1);
    }
    else
    {
        TDownlad *dlst = new TDownlad(0, file_list.at(iterator));
        connect(dlst, SIGNAL(updateProgress(int, int)), this, SLOT(updateDataReadProgress(int,int)));
        dlst->start();
        iterator++;
        ui->total_pbar->setValue(ui->total_pbar->value()+1);
        QEventLoop loop;
        if (iterator == file_list.size())
            connect(dlst, SIGNAL(done()), &loop, SLOT(quit()));
        else
        {
            connect(dlst, SIGNAL(done()), this, SLOT(nextDl()));
            connect(dlst, SIGNAL(done()), &loop, SLOT(quit()));
        }
        if (iterator != file_list.size())
            loop.exec();
        else
        {
            QEventLoop loop;
            connect(dlst, SIGNAL(done()), &loop, SLOT(quit()));
            loop.exec();
        }
        dlst->wait();
        delete dlst;
    }
}

void MainWindow::dlError()
{
    qDebug() << "have error: iterator: " << iterator;
}

void MainWindow::fullCheck()
{
    ui->FC_boutton->setEnabled(false);
    ui->start_boutton->setEnabled(false);
    isFullCheck = true;
    //ui->total_pbar->setMaximum(1);
    ui->total_pbar->setMaximum(file_list.size());

    ui->total_pbar->setValue(ui->total_pbar->maximum());
    file_list = QStringList();
    ui->statusLabel->setText(tr("Checking File."));
    QString fileName("update.lst");
    QFile fichier(fileName);
    fichier.open(QIODevice::ReadOnly);
    QTextStream flux(&fichier);
    QString ligne;
    while(!flux.atEnd())
    {
        ligne = flux.readLine();
        if (ligne == "[misc]")
        {
            ligne = flux.readLine();
            addr_server = ligne.section('=', 1, 1);
        }
        else if (ligne == "[files]")
        {
            ligne = flux.readLine();
            file_count = ligne.section('=', 1, 1).toInt();
            int i = 0;
            while (i < file_count)
            {
               ligne = flux.readLine();
               file_list.append(ligne.section('=', 1, 1).section('|', 0, 0));
               hash_list.append(ligne.section('|', 1, 1));
               i++;
            }
        }
    }
    QStringListModel *modele = new QStringListModel(file_list);
    ui->lv->setModel(modele);
    ui->total_pbar->setMaximum(file_list.size());
    ui->total_pbar->setValue(0);
    if (file_list.size() == 0)
    {
        ui->total_pbar->setMaximum(1);
        ui->total_pbar->setValue(ui->total_pbar->maximum());
    }
    else
    {
        iterator = 0;
        this->nextDl();
    }
    ui->statusLabel->setText(tr("your application is up to date click on sart for launch"));
    //isFullCheck = false;
    ui->FC_boutton->setEnabled(true);
    ui->start_boutton->setEnabled(true);
}

void MainWindow::closeEvent ( QCloseEvent * event )
{
    if (QFile::exists(QString("update.lst"))) {
        QFile::remove(QString("update.lst"));
    }
    close();
}

void MainWindow::my_quit()
{
    if (QFile::exists(QString("update.lst"))) {
        QFile::remove(QString("update.lst"));
    }
    close();
}

void MainWindow::updateDataReadProgress(int bytesRead, int totalBytes)
{
    ui->current_pbar->setMaximum(totalBytes);
    ui->current_pbar->setValue(bytesRead);
}

void MainWindow::execute()
{
    if (QProcess::startDetached("\"system/L2.exe\""))
        this->my_quit();
}
